<template>
    <div class="authorization">
        <el-card class="box-card-left">
            <div slot="header" class="clearfix">
                <span>用户列表</span>
            </div>
            <el-input v-model="searchUserName" size="mini" placeholder="输入用户名搜索" >
                <el-button slot="append" icon="el-icon-search" @click="getUserFullList"></el-button>
            </el-input>
            <el-table ref="userTable" :data="users" style="width: 100%" @row-click="userClick" highlight-current-row>
                <el-table-column prop="name" label="用户名"></el-table-column>
                <el-table-column label="密码">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.password" show-password></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column min-width="120px" label="操作">
                    <template slot-scope="scope">
                        <el-popconfirm title="确定删除吗？" @onConfirm="deleteUser(scope.$index, scope.row)">
                            <el-button slot="reference" size="mini" type="danger" >删除</el-button>
                        </el-popconfirm>
                        <el-button slot="reference" size="mini" type="success" @click="updatePw(scope.$index, scope.row)">修改密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
                <el-pagination
                        @size-change="pageSizeChange"
                        @current-change="pageCurrentChange"
                        :current-page="nowPage"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>

        </el-card>
        <el-card class="box-card-right">
            <div slot="header" class="clearfix">
                <span>角色列表</span>
            </div>
            <el-transfer v-model="selectRoles" :data="roles" :titles="['未拥有角色列表', '已拥有角色列表']"
                         :button-texts="['移除', '添加']">
                <el-button type="success" class="transfer-footer" slot="right-footer" size="small" @click="updateRoles">保存</el-button>
            </el-transfer>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: "Authorization",
        data(){
            return {
                users:[],
                //选中的角色id
                selectRoles:[],
                //全部角色
                roles:[],
                roleAllList: [],
                nowPage: 1,
                pageSize: 10,
                total: 0,
                //用户名筛选
                searchUserName:'',
                //选中的userid
                nowUser: {}


            }
        },
        mounted() {
            this.getUserFullList();
        },
        methods:{
            /**
             * 修改密码
             */
            updatePw(index,row) {
                let _this=this;
                _this.$prompt('请输入新密码', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(({ value }) => {
                    if (value == null || value.length == 0) {
                        _this.$message.error("新密码不能为空");
                        return false;
                    }
                    if (value.length > 20) {
                        _this.$message.error("新密码长度不能大于20");
                        return false;
                    }
                    // var param = _this.$Qs.stringify({newPw: value});
                    //修改密码
                    _this.$axios({
                        url:"user/"+row.id+"/pw",
                        method:"POST",
                        headers:{'Content-Type': 'application/x-www-form-urlencoded'},
                        data:_this.$Qs.stringify({newPw: value})
                    }).then(res=>{
                        let result= res.data;
                        if (result.status == 200) {
                            _this.$message.success(result.message);
                            //密码更新到列表上
                            row.password = value;
                        }else if (result.status == 500) {
                            _this.$message.error(result.message);
                        }
                    })
                })

            },
            getUserFullList() {
                let _this = this;
                var param={
                    nowPage:_this.nowPage,
                    pageSize:_this.pageSize,
                    userName:_this.searchUserName
                }
                _this.$axios.get('user/users',{params:param})
                .then(res => {
                    let result= res.data;
                    if (result.status == 200) {
                        _this.users=result.data.list;
                        _this.total = result.data.total;
                        _this.nowPage = result.data.pageNum;
                        //执行之前先清空
                        _this.selectRoles = [];
                        _this.roles = [];
                        _this.computerRoleAll();
                        if (_this.users != null && _this.users.length > 0) {
                            _this.$refs.userTable.setCurrentRow(_this.users[0]);
                            _this.nowUser = _this.users[0];
                            if (_this.users[0].roleList!=null&&_this.users[0].roleList.length > 0) {
                                _this.computerRoleShow(_this.users[0].roleList);
                            }
                        }
                    }else if (result.status == 500) {
                        _this.$message.error(result.message);
                    }
                })

            },
            computerRoleShow(roles) {
                for (let index in roles) {
                    let role=roles[index];
                    this.selectRoles.push(role.id);
                }
            },
            computerRoleAll() {
                let _this = this;
                _this.$axios.get("role/all")
                    .then(res=>{
                        let result= res.data;
                        if (result.status == 200) {
                            let roleList=result.data;
                            _this.roleAllList = roleList;
                            for (let index in roleList) {
                                let role = roleList[index];
                                _this.roles.push({
                                    key: role.id,
                                    label: role.explanation
                                })
                            }
                        }else if (result.status == 500) {
                            _this.$message.error(result.message);
                        }
                    })
            },
            //点击某一行
            userClick(row) {
                //执行之前先清空
                this.selectRoles = [];
                this.roles = [];
                this.nowUser = row;
                this.computerRoleAll();
                if (row.roleList.length > 0) {
                    this.computerRoleShow(row.roleList);
                }
            },
            deleteUser(index, row) {
                let id=row.id;
                let _this = this;
                _this.$axios.delete("user/delete/" + id)
                .then(res=>{
                    let result= res.data;
                    if (result.status == 200) {
                        _this.$message.success(result.message);
                        _this.getUserFullList();
                    }else if (result.status == 500) {
                        _this.$message.error(result.message);
                    }
                })
            },
            //修改用户角色
            updateRoles() {
                let _this = this;
                var param = JSON.stringify(_this.selectRoles);
                _this.$axios.put("user/" + _this.nowUser.id+"/roles",param,{
                    headers:{'Content-Type': 'application/json'}
                })
                    .then(res=>{
                        let result= res.data;
                        if (result.status == 200) {
                            _this.$message.success(result.message);
                            _this.setNowUserRoles();
                            // _this.getUserFullList();
                        }else if (result.status == 500) {
                            _this.$message.error(result.message);
                        }
                    })
            },
            setNowUserRoles() {
                this.nowUser.roleList = [];
                let nowUser;
                //查找当前user
                for (let i in this.users) {
                    if (this.nowUser.id == this.users[i].id) {
                        nowUser = this.users[i];
                    }
                }
                for (let index in this.roleAllList){
                   let role= this.roleAllList[index];
                    if (this.selectRoles.indexOf(role.id) != -1) {
                        nowUser.roleList.push(role);
                    }
                }
            },
            //分页发生变化
            pageSizeChange(index) {
                this.pageSize = index;
                this.getUserFullList();
            },
            pageCurrentChange(index) {
                this.nowPage = index;
                this.getUserFullList();
            },
        }
    }
</script>

<style scoped>
    .box-card-left{
        width: 45%;
        float: left;
    }
    .box-card-right{
        width: 53%;
        float: right;
    }
    .transfer-footer {
        margin-left: 20px;
        padding: 6px 5px;
    }

</style>